/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.texous.demo.dsj.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public class JsonUtils {
    private static TypeFactory TYPE_FACTORY = TypeFactory.defaultInstance();
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * Returns object as JSON encoded string
     *
     * @param input the bean instance
     * @return Returns single line JSON string
     */
    public static String serialize(Object input) throws JsonProcessingException {
        return OBJECT_MAPPER.writeValueAsString(input);
    }

    /**
     * Returns JSON encoded string as real object
     *
     * @param input the encoded JSON string
     * @return Returns PoJo
     */
    public static <T> T deserialize(String input, Class<T> tClass) throws IOException {
        return OBJECT_MAPPER.readValue(input, tClass);
    }

    /**
     * 将 JSON 格式的字符串转换为 map
     * @param content content
     * @return
     */
    public static Map<String, Object> string2Map(String content) {
        JavaType type = TYPE_FACTORY.constructMapType(HashMap.class, String.class, Object.class);
        try {
            return OBJECT_MAPPER.readValue(content, type);
        } catch (Exception e) {
            FormattingTuple message = MessageFormatter.format("将字符串[{}]转换为Map时出现异常", content);
            throw new RuntimeException(message.getMessage(), e);
        }
    }

    /***/
    public static <T> T readJsonFromUrl(String url, Class<T> tClass) throws Exception {
        try (InputStream is = new URL(url).openStream()) {
            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            return JsonUtils.deserialize(jsonText, tClass);
        }
    }

    private static String readAll(Reader rd) throws Exception {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }
}
